<?php
namespace app\admin\controller;
use think\Db;

class Article
{
	public function __construct(){
		Admin_auth();
	}
	
    public function index()
    {
		$aid = request()->request('aid');
		$where = null;
		if(!empty($aid)){
		    $where['aid'] = $aid;
        }
		$pages = pages('article',$where,input('get.page'));
		$data = Db::table("article")->whereIn('aid',session('aid'))->where($where)->limit($pages['limit'])->order('time desc')->select();
        return view('',['data'  => $data,'pages' => $pages['pages']]);
    }
	
	public function edit()
    {
		$id = input("get.id")?input("get.id"):0;
		if(request()->isPost()){
			$data = input("post.");
			if($id){
				Db::table("article")->where(['id' => $id])->update($data);
			}else{
				$data['time'] = time();
				$id = Db::table("article")->insertGetId($data);
			}
		}
		$data = Db::table("article")->where(['id' => $id])->find();
        return view('',['data'  => $data]);
    }
	
	public function del()
    {
		$id = input("get.id")?input("get.id"):0;
		$page = input("get.page");
		Db::table("article")->delete($id);
		redirect(url('/admin/article').'?page='.$page);
		exit;
    }
	
	public function category()
    {
		$data = array();
		$category = Db::table("article_category")->where('gid',0)->select();
		if(!empty($category)){
			foreach($category as $sub){
				$sub['sub'] = Db::table("article_category")->where('gid',$sub['id'])->select();
				Array_push($data,$sub); 
			}
		}
        return view('',['data'  => $data]);
    }
	
	public function category_edit()
    {
		$id = input("get.id")?input("get.id"):0;
		$data = array();
		if(request()->isPost()){
			$data = input("post.");
			
			if($id){
				Db::table("article_category")->where(['id' => $id])->update($data);
			}else{
				Db::table("article_category")->insert($data);
			}
			$return = array(
				'code' => 'success',
				'msg' => lang('currency')['success']
			);
			return $return;
		}  
    }
	
	public function category_del()
    {
		$id = input("get.id")?input("get.id"):0;
		Db::table("article_category")->delete($id);
		Db::table("article")->where('cid',$id)->delete();
		Db::table("article_category")->where('gid',$id)->delete();
		Db::table("article")->where('gid',$id)->delete();
		$return = array(
				'code' => 'success',
				'msg' => lang('currency')['success']
			);
		return $return;
    }
	
	public function ajax_get()
    {
		$gid = input('get.id')?input('get.id'):0;
		$data = Db::table("article_category")->where(['gid'=>$gid])->order('id asc')->select();
		$return = array(
			'data' => $data
		);
		return $return;
    }
}
